import { ApplicationRef, ComponentFactoryResolver, ComponentRef, EmbeddedViewRef, Injectable } from '@angular/core';
import { DialogRef } from './dialogRef';

@Injectable()
export class DialogService {
    //private loadRef: DialogRef<LoadComponent>;
    constructor(
        private appRef: ApplicationRef,
        private compFactRes: ComponentFactoryResolver
    ) {

    }
    open<T>(component: ComponentType<T>, config: any) {
        const factory = this.compFactRes.resolveComponentFactory(component);
        const dialogRef = new DialogRef(factory, config);
        window.document.body.appendChild(this.getComponentRootNode(dialogRef.componentRef()));
        this.appRef.attachView(dialogRef.componentRef().hostView);
        return dialogRef;
    }
    private getComponentRootNode(componentRef: ComponentRef<any>):HTMLElement {
        return (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    }
}
export interface ComponentType<T> {
    new (...args: any[]): T;
}